package com.tian.service.impl.management;


import com.tian.entity.Menu;
import com.tian.entity.Role;
import com.tian.entity.RoleMenu;
import com.tian.mapper.MenuMapper;
import com.tian.mapper.RoleMapper;
import com.tian.mapper.RoleMenuMapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * {@code @description:} 初始化角色和权限数据到redis缓存
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-09-13 22:50
 * {@code @version:} 1.0
 */
@Slf4j
@Component
public class RolePermissionService {
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private MenuMapper menuMapper;

    @Resource
    private RedissonClient redissonClient;

    @PostConstruct // 注解确保在应用启动时执行此方法
    public void saveRolesAndPermissionsToRedis() {
        this.initCache();
    }
    public  void initCache(){
        log.info("初始化角色和权限数据到redis缓存");
        // 1. 查询所有角色
        List<Role> roleIdList = roleMapper.selectAll();
        for (Role role : roleIdList) {
            // 2. 查询所有菜单
            List<RoleMenu> allRoleMenus = roleMenuMapper.selectByRoleId(role.getId());
            if(CollectionUtils.isEmpty(allRoleMenus)){
                continue;
            }
            redissonClient.getBucket(role.getId().toString()).delete();
            // 3. 查询所有菜单
            List<Menu> menuList = menuMapper.selectByMenuIds(allRoleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList()));
            // 4. 保存角色和菜单到redis缓存(每个角色对应一个redis缓存菜单)
            redissonClient.getBucket(role.getId().toString()).set( menuList);
        }
        log.info("初始化角色和权限数据到redis缓存完成");
    }
}
